from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework_extensions import mixins
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializer import SKUSerializer
from users import constants
from users import serializers
from users.models import User, Address

# 判断用户名是不是存在的
# 1 定义视图函数，接受参数，查看数据库中是不是存在相应的数据，返回ｊｓｏｎ数据给前段
# 2 定义路由
from users.serializers import EmailSerializer, UserAddressSerializer, AddUserBrowsingHistorySerializer
from users.utils import check_verify_email_token


class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            "username": username,
            "count": count
        }
        return Response(data=data)


# 判断手机号码手不是存在
# 和验证用户名过程相似
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data=data)


# 注册用户
# 要点：１　该操作涉及到数据库的新增数据，所以视图函数可以继承于ListAPIView
# 　　　2 　需要新增序列化器(重点)
#      3   数据的校验定义在序列化器中，视图中只是调用序列化器
# 步骤　１　定义序列化器，校验数据的正确
# 　　　２　定义视图
# 　　　３　定义路由

class UserView(CreateAPIView):
    serializer_class = serializers.CreateUserSerializer


# 用户登陆的视图　无需在此处进行定义,ＪＷＴ框架已经实现了登陆的功能，
# 仅需要根据需要返回的函数，重写编写相应的函数

class UserDetailView(APIView):
    """用户信息视图"""
    # 权限判断[这个页面必须是登陆后的用户才能访问到]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取当前登陆用户[request.user 获取当前已经登陆的用户了]
        user = request.user

        # 响应数据
        return Response({
            "id": user.id,
            "username": user.username,
            "mobile": user.mobile,
            "email": user.email,
            "email_active": user.email_active,
        })


class EmailView(UpdateAPIView):
    """用户邮箱保存视图"""
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """因为地址栏上面没有pk这个url参数，所以我们需要重写get_object获取指定的用户信息"""
        return self.request.user


class VerifyEmailView(APIView):
    """更新邮箱激活状态视图"""

    def get(self, request):
        # 1. 获取token提取里面的user.id
        try:
            token = request.query_params.get("token")
        except Exception:
            return Response({"message": "无效的token"}, status=status.HTTP_400_BAD_REQUEST)

        user_id = check_verify_email_token(token)
        # 1 用户的链接失效或者不存在
        if user_id is None:
            return Response({"message": "无效的token"}, status.HTTP_400_BAD_REQUEST)

        # 2 根据user_id 获取用户的信息
        try:
            user = User.objects.get(pk=user_id)
        except:
            return Response({"message": "无效的token"}, status=status.HTTP_400_BAD_REQUEST)

        # 3 用户存在，修改数据库中相应的字段
        user.email_active = True
        user.save()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)


class AddressesViewSet(ModelViewSet):
    """用户的收货地址视图集"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)

        user = self.request.user

        return Response({
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            "default_address_id": user.default_address,
            "addresses": serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        # 有疑问，request.user.addresses是不是有参数，因为
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        # 本次请求中pk值对应的收货地址
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowsingHistoryView(CreateAPIView):
    """
    1 用户浏览商品的视图，继承与create，调用了post方法
    2 同时在该视图上自定义了get方法
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取浏览历史记录"""
        # 从redis中获取当前用户的user_id
        user_id = request.user.id

        # 从redis获取浏览历史记录
        redis_conn = get_redis_connection("history")
        history = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        skus = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus, many=True)

        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户验证的视图
    """
    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        # 如果用户登录认证成功，则合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, user, response)

        return response

